package bgpemulation;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;


public class ProtocolMessage implements Serializable{
	

	private static final long serialVersionUID = 1L;
	private BGPRoutingTable rt;
	private int asn;
	
	public ProtocolMessage(int asn, BGPRoutingTable rt){
		this.rt = rt;
		this.asn = asn;
	}

	public BGPRoutingTable getRoutingTable() {
		return rt;
	}

	public int getASN() {
		return asn;
	}

	public static byte[] buildPayload(Byte asNumber, BGPRoutingTable bgpRoutingTable) {
		ProtocolMessage pm = new ProtocolMessage(asNumber, bgpRoutingTable);
		try{
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(bos);
			oos.writeObject(pm);
			byte[] obj = bos.toByteArray();
			byte[] ret = new byte[obj.length + 1];
			for(int i = 0; i<obj.length; i++){
				ret[i+1] = obj[i];
			}
			return ret;
		} catch(IOException e){
			e.printStackTrace();
			System.exit(1);
		}
		return null;
	}

	public static ProtocolMessage getPayload(byte[] payload){
		ProtocolMessage pm = null;
		try{
			byte[] serObj = new byte[payload.length - 1];
			for(int i = 1; i<payload.length; i++){
				serObj[i-1] = payload[i];
			}
			ByteArrayInputStream bis = new ByteArrayInputStream(serObj);
			ObjectInputStream ois = new ObjectInputStream(bis);
			pm = (ProtocolMessage)ois.readObject();
		} catch (Exception e){
			e.printStackTrace();
			System.exit(1);
		}
		return pm;
	}
}
